package com.google.code.shardbatis.util;

import java.util.Comparator;
import java.util.List;

import com.google.code.shardbatis.converter.SqlConverterOrderBy;

public class CustomComparator implements Comparator<Object> {

	private List<SqlConverterOrderBy> orderBys = null;
	
	public CustomComparator(List<SqlConverterOrderBy> orderBys) {
		this.orderBys = orderBys;
	}
	
	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public int compare(Object obj1, Object obj2) {
		for (SqlConverterOrderBy orderBy : orderBys) {
			Object field1 = ReflectionUtils.getFieldValue(obj1, orderBy.getFieldName());
			Object field2 = ReflectionUtils.getFieldValue(obj2, orderBy.getFieldName());
			if (field1 instanceof Comparable) {
				int c = ((Comparable)field1).compareTo(field2);
				if (0 == c) { }
				else {
					return orderBy.isAsc() ? c : 0 - c;
				}
			}
		}
		return 0;
	}

}
